package com.example.controller;

import com.example.entity.RestBean;
import com.example.service.ImageService;
import com.example.utils.Const;
import io.minio.MinioClient;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @Author: shenjianZ
 * @Date: 2024/4/29 下午12:52
 * @Description:
 */

@Slf4j
@RestController
@RequestMapping("/api/image")
public class ImageController {
    @Resource
    ImageService imageService;


    @PostMapping("/cache")
    public RestBean<String> uploadImage(@RequestParam("file") MultipartFile file,
                                        @RequestAttribute(Const.ATTR_USER_ID) int id,
                                        HttpServletResponse response) throws IOException {

        if (file.getBytes().length > 1024 * 1024 * 5)
            return RestBean.failure(400, "图片大小不能超过5M");
        log.info("正在上传图片...");
        String imageURL = imageService.uploadImage(file, id);
        if (imageURL == null) {
            log.error("上传图片失败");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return RestBean.failure(400, "上传图片失败,请联系管理员!");
        }
        log.info("上传图片成功 大小：{} ImageURL：{}", file.getSize(), imageURL);
        return RestBean.success(imageURL);
    }

//        String avatarURL = imageService.cacheImage(url);
//        if (avatarURL == null) {
//            log.error("缓存图片失败");
//            return RestBean.failure(400, "缓存图片失败,请联系管理员!");
//        }
//        log.info("缓存图片成功 大小：{} avatarURL：{}", url, avatarURL);
//        return RestBean.success(avatarURL);


    @PostMapping("/avatar")
    public RestBean<String> uploadAvatar(@RequestParam("file") MultipartFile file,
                                         @RequestAttribute(Const.ATTR_USER_ID) int id) throws IOException {
        if (file.getBytes().length > 1024 * 1024)
            return RestBean.failure(400, "图片大小不能超过1M");
        log.info("正在上传头像...");
        String avatarURL = imageService.uploadAvatar(file, id);
        if (avatarURL == null) {
            log.error("上传头像失败");
            return RestBean.failure(400, "上传头像失败,请联系管理员!");
        }
        log.info("上传头像成功 大小：{} avatarURL：{}", file.getSize(), avatarURL);
        return RestBean.success(avatarURL);
    }


    @PostMapping("/upload")
    public void uploadFile(@RequestParam("file") MultipartFile file,
                           @RequestAttribute(Const.ATTR_USER_ID) int id) throws IOException {
        if (file.getBytes().length > 1024 * 1024)
            throw new RuntimeException("图片大小不能超过1M");
        String avatarURL = imageService.uploadAvatar(file,id);
        log.info("上传头像成功");
    }

}
